package com.rw.engine.permission.interceptor;

import com.rw.engine.permission.anno.Permission;
import com.rw.engine.permission.exception.PermissionException;
import com.rw.tool.util.string.StringUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 默认的权限过滤器
 * 它会获取Spring容器中的RoleGetter
 * 并且通过接口获取Role对象，然后获取权限
 * <p>
 * 所以在使用这个过滤器的时候，一定要注入自定义的RoleGetter
 */
public class DefaultPermissionFilterRule implements PermissionFilterRule {
    @Resource
    private RoleGetter roleGetter;

    @Override
    public void filter(Permission permission, HttpServletRequest request) {
        // 获得角色
        Role role = roleGetter.getRole(request);
        if (role == null) {
            throw new IllegalArgumentException("RoleGetter not found in SpringContext!");
        }
        // 获得接口上的权限标识
        String[] value = permission.value();
        List<String> permissionList = Arrays.asList(value);

        // 比对权限
        if (!hasPermission(value) && !role.getPermissions().containsAll(permissionList)) {
            throw new PermissionException("Insufficient permissions!", permissionList, role);
        }
    }

    private boolean hasPermission(String[] value) {
        return value.length == 1 && StringUtil.equals(value[0], Permission.NO_PERMISSION);
    }
}
